<template>
  <a-modal v-model:visible="visible"
           centered
           :closable="false"
           :keyboard="false"
           :maskClosable="false"
           :title="$t('core.model.division.editTitle')">
    <template #footer>
      <a-button key="back" @click="visible = false">
        {{ $t('core.model.division.cancel') }}
      </a-button>
      <a-button key="submit" type="primary" @click="confirmSubmit">
        {{ $t('core.model.division.confirm') }}
      </a-button>
    </template>
    <a-form
        ref="form"
        :model="formState"
        layout="vertical" :wrapper-col="{span: 24}">
      <a-row>
        <a-col :span="24">
          <a-form-item
              label="行政区划名称："
              name="name"
              :rules="[{ required: true, message: '请输入行政区划名称' }]"
          >
            <a-input v-model:value="formState.name"/>
          </a-form-item>
        </a-col>

      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
              label="行政区划缩写："
              name="shortName"
          >
            <a-input v-model:value="formState.shortName" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
              label="行政区划编码："
              name="code"
              :rules="[{ required: true, message: '请输入行政区划编码' }]">
            <a-input v-model:value="formState.code" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="父级行政区划(点击输入框选择其他区划)："
            name="parentId">
            <a-input-group compact v-if="!useCascader">
              <a-input
                v-model:value="parentNameShow"
                aria-readonly="true"
                @focus="useCascader = true"
                style="width: calc(100% - 80px)" />
              <a-button style="width: 80px;" @click="resetParent">重置</a-button>
            </a-input-group>
<!--            <a-input-->
<!--              v-model:value="parentNameShow"-->
<!--              v-if="!useCascader"-->
<!--              aria-readonly="true"-->
<!--              @focus="useCascader = true">-->
<!--            </a-input>-->
            <!--                v-model:value="formState.parentId"-->
            <a-cascader
                @blur="useCascader=false"
                :autofocus="true"
                v-if="useCascader"
                :options="options"
                :load-data="loadData"
                :placeholder="parentNameShow"
                :change-on-select="true"
                expand-trigger="hover"
                :display-render="displayRender"
                @change="selectChange"
                :fieldNames="{label:'title',value:'key'}"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
              label="序号："
              name="sort"
          >
            <a-input-number
                v-model:value="formState.sort"
                style="width: 100%"
                :min="0" :max="999999999">
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="11">
          <a-form-item
              label="经度："
              name="longitude"
          >
            <a-input-number
                v-model:value="formState.longitude"
                :min="0" :max="180"
                :precision="4">
              <template #addonBefore>
                <a-select v-model:value="formState.longitudeUnit" style="width: 80px">
                  <a-select-option value="°E">东经</a-select-option>
                  <a-select-option value="°W">西经</a-select-option>
                </a-select>
              </template>
              <template #addonAfter>
                <span>{{formState.longitudeUnit}}</span>
              </template>
            </a-input-number>
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item
              label="纬度："
              name="latitude"
          >
            <a-input-number
                v-model:value="formState.latitude"
                :min="0"
                :max="90"
                :precision="4">
              <template #addonBefore>
                <a-select v-model:value="formState.latitudeUnit" style="width: 80px">
                  <a-select-option value="°N">北纬</a-select-option>
                  <a-select-option value="°S">南纬</a-select-option>
                </a-select>
              </template>
              <template #addonAfter>
                <span>{{formState.latitudeUnit}}</span>
              </template>
            </a-input-number>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
  import { defineComponent, reactive, ref, watch, getCurrentInstance, toRaw } from 'vue';
  import { divisonApi } from '@/api/core/division';
  import { message } from 'ant-design-vue';
  export default {
    name: 'EditModel',
    components: {
    },
    data () {
      return {
        useCascader: false,
        visible: false
      }
    },
    methods: {
    },
    setup (props, context) {
      const vue = getCurrentInstance();
      const form = ref()
      const formState = reactive({
        iid: '',
        name: '',
        shortName: '',
        code: '',
        parentId: 0,
        sort: 0,
        level: 0,
        longitude: 0,
        latitude: 0,
        longitudeUnit: '°E',
        latitudeUnit: '°N'
      })

      // 当前行政区划
      const division = ref()

      // 当前行政区划的父行政区划名称、父级行政区划编码、当前行政级别
      const parentName = ref()
      const parentNode = ref()
      const currentLevel = ref()

      // 当先显示的行政区划的父行政区划
      const parentNameShow = ref()
      // 打开弹框
      const open = (division, pName, pNode) => {
        division.value = division
        parentName.value = pName
        parentNode.value = pNode
        currentLevel.value = division.level
        parentNameShow.value = pName
        vue.data.visible = true
        formState.iid = division.iid
        formState.name = division.name
        formState.shortName = division.shortName
        formState.code = division.code
        formState.sort = division.sort
        formState.level = division.level
        formState.longitude = division.longitude
        formState.latitude = division.latitude
        formState.parentId = division.parentId
        formState.longitudeUnit = division.longitudeUnit
        formState.latitudeUnit =  division.latitudeUnit
      }


      // 级联选择器数据
      const options = ref([
        {
          title: '行政区划',
          key: '0',
          isLeaf: false,
          level: 0
        }
      ])

      // 区划级联选择器加载渲染
      const displayRender = ({labels, selectedOptions}) => {
        const len = labels.length
        let res = ''
        for (let i = 0; i < len; i++) {
          res += labels[i]
          if (i !== len - 1) {
            res += '/'
          }
        }
        parentNameShow.value = res
        return res
      }

      // 重置父级行政区划
      const resetParent = () => {
        parentNameShow.value = parentName.value
        formState.parentId = parentNode.value
        formState.level = currentLevel.value
        console.log(formState.parentId, 'formState.parentId')
        console.log(formState.level, 'formState.level')
      }

      // 加载级联选择器
      const loadData = (selectedOptions) => {
        console.log(selectedOptions, '加载')
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        divisonApi.getListTreeByPid({
          pid: selectedOptions[selectedOptions.length - 1].key
        }).then((res) => {
          selectedOptions[selectedOptions.length - 1].children = res.data
          options.value = [...options.value]
        })
      }

      // 修改后的父级行政区划节点
      const changeResNodes = ref()
      // 级联选项选中后
      const selectChange = (value, selectedOptions) => {
        // 修改父级行政区划节点数组
        changeResNodes.value = value
        console.log(changeResNodes.value, 'changeResNodes.value')
        // 将当前选中的节点的key值作为父id
        formState.parentId = value[value.length - 1]
        // 将当前选中的父级行政区划的level + 1 作为当前行政区划的level
        formState.level = selectedOptions[value.length - 1].level + 1
      }
      // 确认提交
      const confirmSubmit = () => {
        form.value.validateFields().then(() => {
          divisonApi.modify(toRaw(formState)).then((res) => {
            if (res.code === 1000) {
              message.success('修改行政区划成功')
              vue.data.visible = false
              // 刷新页面
              context.emit('submit', changeResNodes.value)
            } else {
              message.warn(res.msg)
            }
          })
        }).catch((e) => {})
      }

      return {
        form,
        formState,
        parentName,
        parentNameShow,
        options,
        open,
        loadData,
        selectChange,
        confirmSubmit,
        displayRender,
        resetParent
      }
    }

  }
</script>

<style lang="less" scoped>

</style>
